﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PointAsLine
{
    internal class CornerReg
    {
        /// <summary>
        /// 计算两条线段的夹角（度）
        /// </summary>
        public static double CalculateAngle((PointF2G, PointF2G) seg1, (PointF2G, PointF2G) seg2)
        {
            PointF2G p1 = seg1.Item1;
            PointF2G p2 = seg1.Item2;
            PointF2G p3 = seg2.Item1;
            PointF2G p4 = seg2.Item2;

            // 计算两条线段的方向向量
            PointF2G v1 = new PointF2G(p2.X - p1.X, p2.Y - p1.Y);
            PointF2G v2 = new PointF2G(p4.X - p3.X, p4.Y - p3.Y);

            // 计算夹角（弧度）
            double dotProduct = v1.X * v2.X + v1.Y * v2.Y;
            double mag1 = Math.Sqrt(v1.X * v1.X + v1.Y * v1.Y);
            double mag2 = Math.Sqrt(v2.X * v2.X + v2.Y * v2.Y);
            double cosTheta = dotProduct / (mag1 * mag2);
            double angleRadians = Math.Acos(Math.Max(-1, Math.Min(1, cosTheta)));

            // 转换为角度
            return angleRadians * (180.0 / Math.PI);
        }

        public static int FallbackK(Polyline points, int startIndex, int k)
        {
            for (var i = startIndex + 1; i < k; i++)
            {
                var angle = CalculateAngle((points[startIndex], points[i]), (points[i], points[k]));
                if (angle > 70)
                {
                    return i;
                }
            }
            return k;
        }
    }
}
